package com.hmall.order.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private IOrderDetailService detailService;
    @Autowired
    private IOrderLogisticsService logisticsService;

    @Transactional
    @Override
    public Long createOrder(RequestParams requestParams) {
        Order order = new Order();
        //查询商品
        Long itemId = requestParams.getItemId();
        Item item = itemClient.getById(itemId);
        //基于商品价格,购买数量计算商品总价
        long totalFee = item.getPrice()*requestParams.getNum();
        order.setTotalFee(totalFee);
        order.setPaymentType(requestParams.getPaymentType());
        //TODO 这里写死了userid测试用
        order.setUserId(2L);
        order.setStatus(1);
        //将oeder写入数据库
        this.save(order);
        //将商品信息,orderId写入oederDatail表
        OrderDetail detail = new OrderDetail();
        detail.setOrderId(order.getId());
        detail.setName(item.getName());
        detail.setSpec(item.getSpec());
        detail.setPrice(item.getPrice());
        detail.setNum(requestParams.getNum());
        detail.setItemId(item.getId());
        detail.setImage(item.getImage());
        detailService.save(detail);

        //根据addressId查询User服务,获取地址信息
        Long addressId = requestParams.getAddressId();
        Address address = userClient.findAddressById(addressId);
        //将地址封装
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address,orderLogistics);


        orderLogistics.setOrderId(order.getId());
        logisticsService.save(orderLogistics);
//扣减库存
        //TODO  这里出过一个bug,delete方法名错误
        try {
            itemClient.DeleteById(requestParams.getItemId(), requestParams.getNum());

        } catch (Exception e) {
            throw new RuntimeException("库存不足!");
        }

        return order.getId();
    }
}
